/* ----------------------------------------------------------------------------
* File: quiz_user_profile_impl.cpp
*
* Desc: Implementation for user profile - definition
*
* Created: 07/05/2011, by Alexey Korshunov
* ---------------------------------------------------------------------------- */
#include "quiz_user_profile_impl.h"
#include <fstream>


namespace ModuleManagement
{
	QuizUserProfileManagerImpl::QuizUserProfileManagerImpl(const std::string& FileName)
		throw (Common::Exception)
		: m_FileName(FileName)
	{
		using namespace QuizCore;
		std::fstream file;
		char str[512];
		char *name = NULL, *points = NULL;

		// Open file
		file.open(FileName.c_str());
		if (!file.is_open())
			throw Common::Exception("skype_plugin: ERROR - Unable to open user profile file");

		// Read data
		while(file.good())
		{
			file.getline(str, sizeof(str));

			name = strtok(str, "|");
			points = strtok(NULL, "|");

			if (name != NULL && points != NULL)
			{
				std::string User(name);
				unsigned int Points = atoi(points);
				UserStatisticInfo info(User, Points);
				m_UserInfo.push_back(info);
			}
		}
		file.close();
	}

	QuizUserProfileManagerImpl::~QuizUserProfileManagerImpl()
	{
		// Write user info
		WriteUserInfo();
	}

	const QuizCore::UserStatisticList& QuizUserProfileManagerImpl::GetUserStatisticInfo() const
	{
		return m_UserInfo;
	}

	Common::Error QuizUserProfileManagerImpl::GivePoints(const std::string& User, unsigned int Points)
	{
		using namespace QuizCore;
		for (UserStatisticList::iterator i = m_UserInfo.begin(), ie = m_UserInfo.end(); i != ie; ++i)
		{
			if (i->User == User)
			{
				i->Points += Points;
				return Common::SKYPE_SUCCESS;
			}
		}

		UserStatisticInfo info(User, Points);
		m_UserInfo.push_back(info);
		return Common::SKYPE_SUCCESS;
	}


	Common::Error QuizUserProfileManagerImpl::WriteUserInfo()
	{
		using namespace QuizCore;
		std::fstream file;

		file.open(m_FileName.c_str());
		if (file.is_open())
		{
			for (UserStatisticList::iterator i = m_UserInfo.begin(), ie = m_UserInfo.end(); i != ie; ++i)
			{
				file << i->User.c_str() << "|" << i->Points << std::endl;
			}
			file.close();
		}
		return Common::SKYPE_SUCCESS;
	}
}

